import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class Permute {
    private boolean[] used;
    public List<List<Integer>> permute(int[] nums) {

        int len=nums.length;
        used=new boolean[len];
        List<List<Integer>> res=new ArrayList<>();
        backtrace(0,len,nums,new ArrayDeque<>(),res);
        return res;
    }
    private void backtrace(int index, int len , int nums[], ArrayDeque<Integer>path,List<List<Integer>> res)
    {
        if(index==len){
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < len; i++) {
            if(used[i])continue;
            path.addLast(nums[i]);
            used[i]=true;
            backtrace(index+1,len,nums,path,res);
            path.removeLast();
            used[i]=false;
        }
    }
}
